<?php

namespace App\Service\Video;

use App\Model\VideoLink;
use App\Service\BaseService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
class VideoListService extends BaseService
{
    use \Hyperf\Di\Aop\ProxyTrait;
    use \Hyperf\Di\Aop\PropertyHandlerTrait;
    function __construct(\Hyperf\AsyncQueue\Driver\DriverFactory $driverFactory)
    {
        if (method_exists(parent::class, '__construct')) {
            parent::__construct(...func_get_args());
        }
        $this->__handlePropertyHandler(__CLASS__);
    }
    /**
     * @Inject
     * @var VideoLink
     */
    protected $videoLinkModel;
    /**
     * 返回
     * @var
     */
    private $return;
    /**
     * 版本判断
     * @var
     */
    private $version;
    /**
     * 主控制器
     * @return array
     */
    public function handle() : array
    {
        $this->return = ['total' => 0, 'total_page' => 0, 'page' => 0, 'list' => []];
        $page = $this->request->input('page');
        $limit = 20;
        $this->version = $this->request->input('version', '1.0.0');
        $this->getListData($page, $limit);
        if (!empty($this->return['list'])) {
            $this->pickData();
        }
        return $this->return;
    }
    /**
     * 获取列表数据
     * @param $page
     * @param $limit
     * @return void
     */
    private function getListData($page, $limit) : void
    {
        $where[] = ['status', '=', 1];
        if ($this->version >= '1.0.6') {
            $where[] = ['wx_id', '>', 0];
        } else {
            $where[] = ['wx_id', '=', 0];
        }
        $this->return['total'] = $this->videoLinkModel->where($where)->count() ?? 0;
        $this->return['total_page'] = (int) ceil($this->return['total'] / $limit);
        $this->return['page'] = (int) $page;
        $this->return['list'] = $this->videoLinkModel->where($where)->offset(((int) $page - 1) * $limit)->limit($limit)->select('title as text_content', 'introduce', 'video_cover', 'video_url', 'xcv_url', 'wx_info')->orderBy('sort')->get();
    }
    /**
     * @return void
     */
    private function pickData()
    {
        foreach ($this->return['list'] as &$one) {
            $one['wx_info'] = $one['wx_info'] ? json_decode($one['wx_info'], true) : [];
            $one['link'] = $one['wx_info']['link'] ?? '';
            $one['appid'] = $one['wx_info']['appid'] ?? '';
            $one['original_id'] = $one['wx_info']['original_id'] ?? '';
        }
    }
}